package com.example.thread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TimeTask implements Runnable {
    private final int durationSeconds;
    public TimeTask(int durationSeconds) {
        this.durationSeconds = durationSeconds;
    }
    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < durationSeconds; i++) {
            String currentTime = sdf.format(new Date());
            System.out.println(Thread.currentThread().getName() + " - 当前时间: " + currentTime);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("任务被中断");
                return;
            }
        }

        System.out.println(Thread.currentThread().getName() + " - 任务完成");
    }
}
